#!/usr/bin/env python3
import os
import sys
import time
import inspect
from datetime import datetime
import random

data_dir = "/home/flownotify_upload/"

########################################################################################################################
def DLOG(message):
    frame = inspect.stack()[1]
    filename = frame.filename
    lineno = frame.lineno
    timestamp = datetime.now().strftime('%y%m%d %H:%M:%S')
    print(f"{timestamp}| {message}")
    #rint(f"+++: {timestamp} ({filename}:{lineno}) {message}")

def write_to_file(dir_name, file_name, file_content):
    file_path = os.path.join(dir_name, file_name)
    with open(file_path, "w") as file:
        file.write(file_content)

def create_data_directory(data_dir):
    if data_dir.startswith("/"):  # Absolute path
        abs_data_dir = data_dir
    else:  # Relative path
        script_dir = os.path.dirname(os.path.abspath(__file__))
        abs_data_dir = os.path.join(script_dir, data_dir)
    if not os.path.exists(abs_data_dir):
        os.makedirs(abs_data_dir)

def start_file_generation_loop(cmd_id, interval=2):
    amount = 10
    while True:
        current_date = datetime.now();
        current_ts = int(current_date.timestamp())
        current_time = current_date.strftime("%Y%m%d%H%M%S")
        current_timestr = current_date.strftime("%Y/%m/%d %H:%M:%S")
        house_id = 10000 #random.randint(10000, 10100)
        device_id = 1000 #random.randint(1000, 1100)
        amount = amount+5

        # write to file
        file_name = f"{cmd_id}+{device_id}+{current_ts}.txt"
        file_content = f"{cmd_id}|{amount}|{house_id}|{device_id}\n"
        create_data_directory(data_dir)
        write_to_file(data_dir, file_name, file_content)
        print(f"+++|{current_timestr}|{data_dir}{file_name}|{file_content}")

        time.sleep(interval)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        DLOG(f"error: usage: {sys.argv[0]} <output_path> <cmdid>\n")
        sys.exit(1)
    data_dir = sys.argv[1]
    try:
        os.makedirs(data_dir)
    except OSError as e:
        print(f"error: mkdir {data_dir} fial, errno={str(e)}")
    cmd_id = sys.argv[2]
    start_file_generation_loop(cmd_id)
